﻿
using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Markup;
using System.Globalization;
using System.Xml.Linq;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows.Navigation;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Controls;
using Microsoft.Advertising.Mobile.UI;
using Common.Library;
using OnlineVideos.Library;
using OnlineVideos.UI;
using OnlineVideos.Data;
using OnlineVideos.Common;
//using MyToolkit.Multimedia;
using Common.Utilities;
using OnlineVideos.Entities;



namespace OnlineVideos
{
    public partial class Search : PhoneApplicationPage
    {

        #region Global
       
        List<CastProfile> matchedPeople = null;
        List<ShowList> matchedMovies = null;
        List<ShowLinks> matchedLinks = null;
        List<ShowLinks> matchedaudioLinks = null;
        List<QuizList> matchedSubjects = null;
        string searchText;

        #endregion

        #region Constructor
        public Search()
        {
            try
            {
            InitializeComponent();
            matchedMovies = new List<ShowList>();
            matchedLinks = new List<ShowLinks>();
            matchedaudioLinks = new List<ShowLinks>();
            matchedPeople = new List<CastProfile>();
            matchedSubjects = new List<QuizList>();
            LoadPivotThemes();
            if (ResourceHelper.AppName != Apps.Indian_Cinema_Pro.ToString() && ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() && ResourceHelper.AppName != Apps.Story_Time_Pro.ToString())
            LoadAds();
            }
              
           
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in Search Method In Search file.", ex);
            }
        }
        #endregion

        #region PageLoad
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
               
                FlurryWP8SDK.Api.LogEvent("Search Page", true);
                NavigationContext.QueryString.TryGetValue("searchtext", out searchText);
                //_performanceProgressBar.IsIndeterminate = true;
                GetPageDataInBackground();
                if (pvtMainSearch.Items.Count >= 2)
                    pvtMainSearch.SelectedIndex = 0;
                _performanceProgressBar.IsIndeterminate = false;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Search file.", ex);
            }
        }
        #endregion


        #region "Common Methods"
        
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstSearch, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }


        private void GetPageDataInBackground()
        {
            BackgroundHelper bwHelper = new BackgroundHelper();
            if (!AppResources.ShowCricketDetailPage)
            {
                bwHelper.AddBackgroundTask(
                                           (object s, DoWorkEventArgs a) =>
                                           {

                                               a.Result = SearchManager.GetShowsLinksBySearch(searchText.ToLower(),LinkType.Songs);
                                           },
                                           (object s, RunWorkerCompletedEventArgs a) =>
                                           {
                                               matchedLinks = (List<ShowLinks>)a.Result;
                                               if (matchedLinks.Count > 0)
                                               {
                                                   lbxSearchSongs.ItemsSource = matchedLinks;
                                                   tblkFavNoSongs.Visibility = Visibility.Collapsed;
                                               }
                                               else
                                                  tblkFavNoSongs.Visibility = Visibility.Visible;
                                               if (ResourceHelper.ProjectName == AppResources.VideoMix)
                                               {
                                                   tblkFavNoSongs.Text = "No Video mixes Available";
                                               }
                                               else
                                               {
                                                   tblkFavNoSongs.Text = "No Videos Available";
                                               }
                                           }
                                         );
            }

            if (AppResources.ShowFavoritesPageMoviesPivot)
            {
                bwHelper.AddBackgroundTask(
                                            (object s, DoWorkEventArgs a) =>
                                            {
                                                a.Result = SearchManager.GetShowsBySearch(searchText.ToLower());
                                            },
                                            (object s, RunWorkerCompletedEventArgs a) =>
                                            {
                                                matchedMovies = (List<ShowList>)a.Result;
                                                if (matchedMovies.Count > 0)
                                                {
                                                    lbxVidoes.ItemsSource = matchedMovies;
                                                }
                                                else
                                                {
                                                    tblk.Text = "No " + AppResources.FavoriteMoviesPivotTitle + " available";
                                                    tblk.Visibility = Visibility.Visible;
                                                }
                                            }
                                          );
            }


            if (AppResources.ShowCastPanoramaPage)
            {
                bwHelper.AddBackgroundTask(
                                            (object s, DoWorkEventArgs a) =>
                                            {
                                                a.Result = SearchManager.GetPeopleBySearch(searchText.ToLower());
                                            },
                                            (object s, RunWorkerCompletedEventArgs a) =>
                                            {
                                                matchedPeople = (List<CastProfile>)a.Result;
                                                if (matchedPeople.Count > 0)
                                                {
                                                    lbxCast.ItemsSource = matchedPeople;
                                                }
                                                else
                                                {
                                                    tblkcast.Text = "No " + AppResources.FavoritePeoplePivotTitle + " available";
                                                    tblkcast.Visibility = Visibility.Visible;
                                                }

                                            }
                                          );
            }
            if (AppResources.ShowQuiz)
            {
                bwHelper.AddBackgroundTask(
                (object s, DoWorkEventArgs a) =>
                {
                    a.Result = SearchManager.GetSubjectsBySearch(searchText.ToLower());
                },
                (object s, RunWorkerCompletedEventArgs a) =>
                {
                    matchedSubjects = (List<QuizList>)a.Result;
                    if (matchedSubjects.Count > 0)
                    {
                        lbxSearchQuiz.ItemsSource = matchedSubjects;
                    }
                    else
                    {
                        tblkquiz.Text = "No " + AppResources.ShowQuizPivotTitle + " available";
                        tblkquiz.Visibility = Visibility.Visible;
                    }

                }
                );

            }
            if (AppResources.ShowDetailPageAudioPivot)
            {
                bwHelper.AddBackgroundTask(
                                       (object s, DoWorkEventArgs a) =>
                                       {

                                           a.Result = SearchManager.GetShowsLinksBySearch(searchText.ToLower(),LinkType.Audio);
                                       },
                                       (object s, RunWorkerCompletedEventArgs a) =>
                                       {
                                           matchedaudioLinks = (List<ShowLinks>)a.Result;
                                           if (matchedaudioLinks.Count > 0)
                                           {
                                               lbxSearchAudioSongs.ItemsSource = matchedaudioLinks;
                                               tblkFavNoAudioSongs.Visibility = Visibility.Collapsed;
                                           }
                                           else
                                               tblkFavNoAudioSongs.Visibility = Visibility.Visible;
                                           tblkFavNoAudioSongs.Text = "No " + AppResources.ShowFavoriteAudioPivotTitle + " available";
                                       }
                                     );
            }
            bwHelper.RunBackgroundWorkers();
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.EndTimedEvent("Search Page");
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom Method In Search file.", ex);
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogPageView();
            _performanceProgressBar.IsIndeterminate = true;
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In Search file.", ex);
            }
            //YouTube.CancelPlay();
        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            //if (YouTube.CancelPlay())
            //    e.Cancel = true;

            base.OnBackKeyPress(e);
        }
        private void LoadPivotThemes()
        {
            try
            {
                if (AppResources.ShowCricketDetailPage)
                {
                    pvtitmVideos.Visibility = Visibility.Visible;
                    pvtitmVideos.Header = AppResources.FavoriteMoviesPivotTitle;
                    pvtitmCast.Visibility = Visibility.Visible;
                    pvtitmCast.Header = AppResources.FavoritePeoplePivotTitle;
                    pvtitemAudioSongs.Visibility = Visibility.Collapsed;
                    pvtMainSearch.Items.Remove(pvtitemAudioSongs);
                    pvtitemSongs.Visibility = Visibility.Collapsed;
                    pvtMainSearch.Items.Remove(pvtitemSongs);
                    pvtitemquiz.Visibility = Visibility.Collapsed;
                    pvtMainSearch.Items.Remove(pvtitemquiz);

                    
                }
                else
                {
                    if (ResourceHelper.AppName == Apps.Web_Tile.ToString())
                    {
                        pvtitmVideos.Visibility = Visibility.Visible;
                        pvtitmVideos.Header = AppResources.FavoriteMoviesPivotTitle;
                        pvtitemSongs.Visibility = Visibility.Collapsed;
                        pvtMainSearch.Items.Remove(pvtitemSongs);
                        pvtitemAudioSongs.Visibility = Visibility.Collapsed;
                        pvtMainSearch.Items.Remove(pvtitemAudioSongs);
                        pvtitemquiz.Visibility = Visibility.Collapsed;
                        pvtMainSearch.Items.Remove(pvtitemquiz);
                    }
                    else
                    {
                        if (AppResources.ShowDetailPageAudioPivot)
                        {

                            pvtitemAudioSongs.Visibility = Visibility.Visible;

                            pvtitemAudioSongs.Header = AppResources.FavoriteAudioPivotTitle;
                        }
                        else
                        {
                            pvtitemAudioSongs.Visibility = Visibility.Collapsed;
                            pvtMainSearch.Items.Remove(pvtitemAudioSongs);
                        }



                        if (!AppResources.ShowFavoritesPageMoviesPivot || !AppResources.ShowDetailPageAudioPivot)
                        {
                            pvtitmVideos.Visibility = Visibility.Collapsed;
                            pvtMainSearch.Items.Remove(pvtitmVideos);
                        }
                        else
                        {
                            pvtitmVideos.Visibility = Visibility.Visible;
                            pvtitmVideos.Header = AppResources.FavoriteMoviesPivotTitle;
                        }

                        if (!AppResources.ShowFavouritesPageComedyPivot || !AppResources.ShowDetailPageAudioPivot)
                        {
                            pvtitmComedy.Visibility = Visibility.Collapsed;
                            pvtMainSearch.Items.Remove(pvtitmComedy);
                        }
                        else
                        {
                            pvtitmComedy.Visibility = Visibility.Visible;
                            pvtitmComedy.Header = AppResources.ComedyHistoryPivotTitle;
                        }

                        if (AppResources.ShowDetailPageSongsPivot || !AppResources.ShowDetailPageAudioPivot)
                        {
                            pvtitemSongs.Visibility = Visibility.Visible;
                            pvtitemSongs.Header = AppResources.FavoriteSongsPivotTitle;
                        }
                        else
                        {
                            pvtitemSongs.Visibility = Visibility.Collapsed;
                            pvtMainSearch.Items.Remove(pvtitemSongs);

                        }


                        if (AppResources.ShowCastPanoramaPage)
                        {
                            pvtitmCast.Visibility = Visibility.Visible;
                            pvtitmCast.Header = AppResources.FavoritePeoplePivotTitle;

                        }
                        else
                        {
                            pvtitmCast.Visibility = Visibility.Collapsed;
                            pvtMainSearch.Items.Remove(pvtitmCast);
                        }


                        if (!AppResources.ShowQuiz)
                        {
                            pvtitemquiz.Visibility = Visibility.Collapsed;
                            pvtMainSearch.Items.Remove(pvtitemquiz);
                        }
                        else
                        {
                            pvtitemquiz.Visibility = Visibility.Visible;
                            pvtitemquiz.Header = AppResources.ShowQuizPivotTitle;
                            pvtitemAudioSongs.Visibility = Visibility.Collapsed;
                            pvtMainSearch.Items.Remove(pvtitemAudioSongs);


                        }
                        //if (ResourceHelper.AppName == Apps.Web_Tile.ToString())
                        //{
                        //    pvtitmVideos.Visibility = Visibility.Visible;
                        //    pvtitemSongs.Visibility = Visibility.Collapsed;
                        //    pvtitmVideos.Header = AppResources.FavoriteMoviesPivotTitle;
                        //}
                    }
                }
               
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Search file.", ex);
            }
        }
        #endregion

        #region Events
        void lbxVidoes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxVidoes.SelectedIndex == -1)
                    return;
                AppState.searchtitle = string.Empty;
                AppSettings.ShowID = (lbxVidoes.SelectedItem as ShowList).ShowID.ToString();
                AppSettings.Title = (lbxVidoes.SelectedItem as ShowList).Title.ToString();
                //AppSettings.LinkTitle = (lbxVidoes.SelectedItem as ShowLinks).Title.ToString();
                //AppSettings.LinkType = (lbxVidoes.SelectedItem as ShowLinks).LinkType.ToString();
                NavigationService.Navigate(NavigationHelper.getsearchdetailspage(AppResources.DetailPageName, (lbxVidoes.SelectedItem as ShowList), pvtMainSearch.SelectedItem.GetType().GetProperty("Header").GetValue((object)this.pvtMainSearch.SelectedItem, null).ToString()));


                lbxVidoes.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Search file.", ex);
            }
        }

        private void lbxSearchSongs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxSearchSongs.SelectedIndex == -1)
                    return;
                AppSettings.LinkTitle = (lbxSearchSongs.SelectedItem as ShowLinks).Title.ToString();
                AppSettings.LinkType = (lbxSearchSongs.SelectedItem as ShowLinks).LinkType.ToString();
                if (ResourceHelper.AppName == Apps.Web_Media.ToString())
                {
                    DownloadManagerHelper.Playvideo(int.Parse((lbxSearchSongs.SelectedItem as ShowLinks).ShowID.ToString()));
                }
               else if (!AppResources.IsSimpleDetailPage)
                {
                    AppState.searchtitle = (lbxSearchSongs.SelectedItem as ShowLinks).Title;
                    NavigationService.Navigate(NavigationHelper.getMovieDetailPageFromSearch((lbxSearchSongs.SelectedItem as ShowLinks), pvtMainSearch.SelectedItem.GetType().GetProperty("Header").GetValue((object)this.pvtMainSearch.SelectedItem, null).ToString()));
                }
                else
                {
                    AppSettings.ShowID = (lbxSearchSongs.SelectedItem as ShowLinks).ShowID.ToString();
                    AppState.searchtitle = (lbxSearchSongs.SelectedItem as ShowLinks).Title;
                    if(ResourceHelper.AppName==Apps.World_Dance.ToString())
                        NavigationService.Navigate(NavigationHelper.getDanceDetailPageFromSearch((lbxSearchSongs.SelectedItem as ShowLinks), pvtMainSearch.SelectedItem.GetType().GetProperty("Header").GetValue((object)this.pvtMainSearch.SelectedItem, null).ToString()));
                    else
                    PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
                } lbxSearchSongs.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                lbxSearchSongs.SelectedIndex = -1;
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Search file.", ex);
            }
        }
        private void lbxCast_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxCast.SelectedIndex == -1)
                    return;
                FlurryWP8SDK.Api.LogEvent((lbxCast.SelectedItem as CastProfile).Name.ToString() + " Gallery Watched");
                AppSettings.PersonID = (lbxCast.SelectedItem as CastProfile).PersonID.ToString();

                if (AppResources.ShowCastPanoramaPage && (ResourceHelper.AppName != Apps.Kids_TV_Shows.ToString() && ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() &&  ResourceHelper.AppName != Apps.Kids_TV.ToString()))
                    NavigationService.Navigate(NavigationHelper.getCastPanoramaPageFromSearch());
                else if (ResourceHelper.AppName == Apps.Kids_TV_Shows.ToString() || ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString() || ResourceHelper.AppName == Apps.Kids_TV.ToString())
                {
                    NavigationService.Navigate(NavigationHelper.getCharacterDetailPage());
                }
                lbxCast.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Search file.", ex);
            }
        }
        private void lbxSearchQuiz_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxSearchQuiz.SelectedIndex == -1)
                    return;
                AppSettings.ShowID = (lbxSearchQuiz.SelectedItem as QuizList).ShowID.ToString();
                string QuizTitle = (lbxSearchQuiz.SelectedItem as QuizList).Name.ToString();
                AppState.searchtitle = QuizTitle;
                NavigationService.Navigate(NavigationHelper.getSubjectDetailPage((lbxSearchQuiz.SelectedItem as QuizList), QuizTitle));
                lbxSearchQuiz.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                lbxSearchQuiz.SelectedIndex = -1;
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Search file.", ex);
            }
        }
        private void lbxSearchAudioSongs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxSearchAudioSongs.SelectedIndex == -1)
                    return;

                AppSettings.ShowID = (lbxSearchAudioSongs.SelectedItem as ShowLinks).ShowID.ToString();
                AppState.searchtitle = (lbxSearchAudioSongs.SelectedItem as ShowLinks).Title.ToString();
                AppSettings.LinkTitle = (lbxSearchAudioSongs.SelectedItem as ShowLinks).Title.ToString();
                AppSettings.LinkType = (lbxSearchAudioSongs.SelectedItem as ShowLinks).LinkType.ToString();
                if (!AppResources.IsSimpleDetailPage)
                {
                    //Constants.topsongnavigation = "4";
                    NavigationService.Navigate(NavigationHelper.getMovieDetailPageFromSearchMovies((lbxSearchAudioSongs.SelectedItem as ShowLinks), pvtMainSearch.SelectedItem.GetType().GetProperty("Header").GetValue((object)this.pvtMainSearch.SelectedItem, null).ToString()));
                }
               else if (ResourceHelper.AppName == Apps.Web_Media.ToString())
                {
                    //ShowAudio audio = new ShowAudio();
                    //audio.LoadDownLoads(lbxSearchAudioSongs.SelectedItem as ShowLinks);
                    AppSettings.SongID = (lbxSearchAudioSongs.SelectedItem as ShowLinks).LinkID.ToString();
                    AppSettings.AudioImage = (lbxSearchAudioSongs.SelectedItem as ShowLinks).Songplay;
                }
                else
                {
                    Constants.topsongnavigation = "1";
                    NavigationService.Navigate(NavigationHelper.getMovieDetailPageAudio((lbxSearchAudioSongs.SelectedItem as ShowLinks)));
                }
                lbxSearchAudioSongs.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                lbxSearchAudioSongs.SelectedIndex = -1;
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Search file.", ex);
            }
        }
        private void imgTitle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }

        private void lbxComedy_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxComedy.SelectedIndex == -1)
                    return;
                AppState.searchtitle = string.Empty;
                AppSettings.ShowID = (lbxComedy.SelectedItem as ShowList).ShowID.ToString();
                AppSettings.Title = (lbxComedy.SelectedItem as ShowList).Title.ToString();
                //AppSettings.LinkTitle = (lbxVidoes.SelectedItem as ShowLinks).Title.ToString();
                //AppSettings.LinkType = (lbxVidoes.SelectedItem as ShowLinks).LinkType.ToString();
                NavigationService.Navigate(NavigationHelper.getsearchdetailspage(AppResources.DetailPageName, (lbxComedy.SelectedItem as ShowList), pvtMainSearch.SelectedItem.GetType().GetProperty("Header").GetValue((object)this.pvtMainSearch.SelectedItem, null).ToString()));


                lbxVidoes.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In Search file.", ex);
            }
        }
        #endregion
    }
}